# 商城购物系统
# 1.通过users.json文件中读写用户信息，{用户名：{用户密码，用户余额}}
# 2.通过goods.json文件读写商品信息，{商品ID：{商品名，商品价格}}
# 3.登录验证
# 4.登录成功后，可以选择显示所有商品信息、根据商品ID购物、浏览购物车和结算
# 5.结算时根据用户余额进行相应判断，统计已购买的商品和余额，并将结算后的余额写入用户信息
# 6.尽量使用封装函数来完成相应功能

# 读取用户信息和商品信息 load_users load_goods
# 登录验证login -->登录失败  -->重新登录
#             -->登录成功  -->查看账户余额 show_user_balance
#                         -->显示所有商品信息 show_goods
#                         -->进行购物 add_to_cart
#                         -->查看购物车 show_cart
#                         -->结算购物车 checkout -->打印购物车和余额


import json
import os
users = {}
# 读取用户信息
def load_users():
    if os.path.exists("users.json"):
        with open('users.json', 'r', encoding='utf-8') as f:
            users = json.load(f)
    return users


# 保存用户信息
def save_users(users):
    with open('users.json', 'w', encoding='utf-8') as f:
        json.dump(users, f, indent=1)


# 读取商品信息
def load_goods():
    with open('goods.json', 'r', encoding='utf-8') as f:
        goods = json.load(f)
    return goods


# 显示用户账户余额
def show_user_balance(username):
    users = load_users()
    print(f"当前账户余额为：{users[username]['balance']}")


# 显示所有商品信息
def show_goods(goods):
    print("商品列表".center(20, "-"))
    print("商品ID\t商品名\t商品价格")
    for good_id, info in goods.items():
        name, price = info['name'], info['price']
        print(f'{good_id}\t\t{name}\t{price}')


# 添加商品到购物车
def add_to_cart(goods, cart):
    good_id = input("请输入要添加到购物车的商品ID：")
    if good_id not in goods:
        print("商品ID不存在")
        return
    name, price = goods[good_id]['name'], goods[good_id]['price']
    if good_id not in cart:
        cart[good_id] = {'name': name, 'price': price, 'count': 1}
    else:
        cart[good_id]['count'] += 1
    print(f"已成功将{cart[good_id]['name']}添加到购物车")


# 显示购物车内的商品
def show_cart(cart):
    if not cart:
        print("购物车为空")
        return
    print("购物车：".center(20, "-"))
    print("商品名\t价格\t数量\t小计")
    total_price = 0
    for good_id, info in cart.items():
        name, price, count = info['name'], info['price'], info['count']
        item_price = price * count
        total_price += item_price
        print(f"{name}\t{price}\t{count}\t{item_price}")
    print(f"总计：{total_price}")


# 购物车结算
def checkout(users, cart, username):
    if not cart:
        print("购物车为空，无法结算")
        return
    total_price = sum([info['price'] * info['count'] for info in cart.values()])
    if total_price > users[username]['balance']:
        print("余额不足，无法结算")
        return
    users[username]['balance'] -= total_price
    save_users(users)
    print(f"已成功购买以下商品，共计{total_price}元：")
    for good_id, info in cart.items():
        name, price, count = info['name'], info['price'], info['count']
        print(f"{name} 单价：{price} 数量：{count}")
    print(f"账户余额剩余：{users[username]['balance']}")
    cart.clear()


# 主程序
def main():
    users = load_users()
    goods = load_goods()
    print("欢迎来到购物商城".center(20, "-"))
    while True:
        username = input("请输入用户名：")
        if username not in users:
            print("用户名不存在，请重新输入")
            continue

        password = input("请输入密码：")
        if password != users[username]['password']:
            print("密码错误，请重新输入")
            continue
        else:
            print(f"欢迎，{username}")
            break
    cart = {}

    while True:
        print("商城菜单".center(20, "-"))
        print("1.查看账户余额")
        print("2.显示所有商品信息")
        print("3.添加商品到购物车")
        print("4.查看购物车内的商品")
        print("5.购物车结算")
        print("6.退出系统")
        choice = input("请输入序号进行操作：")
        if choice == '1':
            show_user_balance(username)
        elif choice == '2':
            show_goods(goods)
        elif choice == '3':
            add_to_cart(goods, cart)
        elif choice == '4':
            show_cart(cart)
        elif choice == '5':
            checkout(users, cart, username)
        elif choice == '6':
            print("退出购物")
            break
        else:
            print("无效选择，请重新输入")


# 执行主程序
if __name__ == "__main__":
    main()
